import { ProCard } from '@ant-design/pro-components';
import { Col, Divider, Row, Space , Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import { history } from '@umijs/max';
import ActionButtons from './ActionButtons';
import { RESTART_POLICIES } from './constants';
import { EditableField } from './EditableField';
import { useContainerRenderer } from './hooks/useContainerRenderer';
import InfoSection from './InfoSection';
import StatusTag from './StatusTag';

interface ContainerCardProps {
  item: API.DockerComposeVO;
  expandedCards: Record<string, boolean>;
  editingCards: Record<string, boolean>;
  onStart: (id: string) => void;
  onStop: (id: string) => void;
  onRestart: (id: string) => void;
  onRebuild: (id: string) => void;
  onEditFile: (id: string) => void;
  onSaveEdit: (id: string, data: Partial<API.DockerComposeVO>) => void;
  onCancelEdit: (id: string) => void;
  onToggle: (id: string) => void;
  onFetchNetworks?: () => Promise<API.NetworkVariable[]>;
}

const ContainerCard: React.FC<ContainerCardProps> = ({
  item,
  expandedCards,
  editingCards,
  onStart,
  onStop,
  onRestart,
  onRebuild,
  onEditFile,
  onSaveEdit,
  onCancelEdit,
  onToggle,
  onFetchNetworks,
}) => {
  const { renderPortsList, renderVolumesList, renderEnvironmentList } =
    useContainerRenderer();
  const [editData, setEditData] = useState<Partial<API.DockerComposeVO>>({});
  const [networkOptions, setNetworkOptions] = useState<
    Array<{ label: string; value: string }>
  >([]);
  const [networkLoading, setNetworkLoading] = useState(false);

  const isEditing = editingCards[item.id];

  // 初始化编辑数据
  useEffect(() => {
    if (isEditing) {
      setEditData({
        containerName: item.containerName,
        restart: item.restart,
        networks: [...item.networks],
        ports: [...item.ports],
        volumes: [...item.volumes],
        environment: [...item.environment],
      });

      // 获取网络选项
      if (onFetchNetworks) {
        setNetworkLoading(true);
        onFetchNetworks()
          .then((options) => {
            setNetworkOptions(options);
            setNetworkLoading(false);
          })
          .catch(() => {
            setNetworkLoading(false);
          });
      }
    }
  }, [isEditing, item, onFetchNetworks]);

  const handleSave = () => {
    onSaveEdit(item.id, editData);
  };

  const handleCancel = () => {
    setEditData({});
    onCancelEdit(item.id);
  };

  // 镜像未安装处理事件
  const handleNotFoundClick = () => {
    Modal.confirm({
      title: '镜像未安装',
      content: '该镜像尚未安装，是否前往Docker页面进行安装？',
      okText: '去安装',
      cancelText: '取消',
      onOk: () => {
        history.push('/docker');
      }
    });
  };

  return (
    <ProCard
      key={item.id}
      title={item.name}
      extra={
        <ActionButtons
          item={item}
          expandedCards={expandedCards}
          editingCards={editingCards}
          onStart={onStart}
          onStop={onStop}
          onRestart={onRestart}
          onRebuild={onRebuild}
          onEditFile={onEditFile}
          onSaveEdit={handleSave}
          onCancelEdit={handleCancel}
          onToggle={onToggle}
        />
      }
      headerBordered
      bordered
      style={{
        marginBottom: 16,
        cursor: item.status === 'not-found' ? 'pointer' : 'default',
        ...(isEditing && { borderColor: '#1890ff' }),
      }}
      onClick={() => item.status === 'not-found' && handleNotFoundClick()}
    >
      <div>
        <Space
            style={{
              cursor: item.status === 'not-found' ? 'pointer' : 'default'
            }}
        >
          <strong>状态：</strong>
          <StatusTag status={item.status} />
        </Space>

        {expandedCards[item.id] && (
          <>
            <Divider />
            <Row gutter={[16, 16]} align="top">
              {/* 左侧 */}
              <Col span={12} style={{ display: 'flex', flexDirection: 'column' }}>
                <InfoSection title="镜像">
                  <EditableField
                      value={item.image}
                      isEditing={false}  // 永远设为只读
                      onChange={() => {}}  // 空函数
                  />
                </InfoSection>

                <InfoSection title="重启策略">
                  <EditableField
                    value={
                      isEditing
                        ? editData.restart || item.restart
                        : item.restart
                    }
                    isEditing={isEditing}
                    type="select"
                    options={[...RESTART_POLICIES]} // 创建新数组以解除 readonly 限制
                    onChange={(value) =>
                      setEditData((prev) => ({ ...prev, restart: value }))
                    }
                  />
                </InfoSection>

                <InfoSection title="端口映射">
                  {renderPortsList(
                    isEditing ? editData.ports || [] : item.ports,
                    isEditing,
                    (ports) => setEditData((prev) => ({ ...prev, ports })),
                  )}
                </InfoSection>

                <InfoSection title="环境变量">
                  {renderEnvironmentList(
                    isEditing ? editData.environment || [] : item.environment,
                    isEditing,
                    (environment) =>
                      setEditData((prev) => ({ ...prev, environment })),
                  )}
                </InfoSection>
              </Col>

              {/* 右侧 */}
              <Col span={12} style={{ display: 'flex', flexDirection: 'column' }}>
                <InfoSection title="容器名">
                  <EditableField
                    value={
                      isEditing
                        ? editData.containerName || item.containerName || ''
                        : item.containerName || '-'
                    }
                    isEditing={isEditing}
                    onChange={(value) =>
                      setEditData((prev) => ({ ...prev, containerName: value }))
                    }
                  />
                </InfoSection>

                <InfoSection title="网络模式">
                  <EditableField
                    value={
                      isEditing
                        ? editData.networks?.join(', ') || ''
                        : item.networks.join(', ') || '-'
                    }
                    isEditing={isEditing}
                    type="select"
                    options={networkOptions}
                    loading={networkLoading}
                    onChange={(value) =>
                      setEditData((prev) => ({ ...prev, networks: [value] }))
                    }
                  />
                </InfoSection>

                <InfoSection title="卷挂载">
                  {renderVolumesList(
                    isEditing ? editData.volumes || [] : item.volumes,
                    isEditing,
                    (volumes) => setEditData((prev) => ({ ...prev, volumes })),
                  )}
                </InfoSection>
              </Col>
            </Row>
          </>
        )}
      </div>
    </ProCard>
  );
};

export default ContainerCard;
